package com.heima.admin.service.Impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdLoginDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Override
    public ResponseResult login(AdLoginDto adLoginDto) {
        //参数检查
        if (adLoginDto == null || StringUtils.isEmpty(adLoginDto.getName()) || StringUtils.isEmpty(adLoginDto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, adLoginDto.getName()));

        if (adUser == null) {
            return ResponseResult.okResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        String verifyPasswd = DigestUtils.md5DigestAsHex((adUser.getSalt() + adLoginDto.getPassword()).getBytes());

        if (verifyPasswd.equals(adUser.getPassword())) {
            //返回数据 jwt
            Map<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(adUser.getId().longValue()));
            adUser.setPassword("");
            adUser.setSalt("");
            map.put("user",adUser);
            return ResponseResult.okResult(map);
        } else {
            return ResponseResult.okResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
    }
}
